#coding:utf-8
import random
import MySQLdb
import time
import functools
import random
import numpy as np
import matplotlib.pyplot as plt

"""
@author:自之梦 10061661
@time: 17/10/26 上午10:26
#统计商家订单情况
"""


def fn_time(fuc):
    @functools.wraps(fuc)
    def function_time(*args, **kwargs):
        t0 = time.time()
        result = fuc(*args, **kwargs)
        t1 = time.time()
        Use_time = int(float( '%.3f' % (t1 - t0))*1000)
        print ("Total time running %s: %sms" %
               (fuc.func_name, str(Use_time))
               )
        return result
    return function_time


def log(fuc):
    @functools.wraps(fuc)
    def wrapper(*args, **kwargs):
        print "-"*32,"\n"
        print "%s fuc start ..." % fuc.__name__
        t1 = time.time()
        result = fuc(*args, **kwargs)
        t2 = time.time()
        time_Val = int(float( '%.3f' % (t2 - t1))*1000)
        print "%s fuc end ..." % fuc.__name__
        print "{1} fuc total running :{0}ms".format(str(time_Val), fuc.__name__)
        print "-"*32
        return result
    return wrapper


@log
#@fn_time
def get_sku_for_Db(sql):
    
    print "start..."
    db = MySQLdb.connect(
        host="10.10.111.240",
        port = 3306,
        user = "omsmanger",
        passwd = "alog@123",
        db = "oms",
        charset='utf8'
        )
    cursor = db.cursor()
    
    #随机获取ljj(ljj的merchant_id是1)商家10个SKU
    
    
    """
    sql = {"total":"SELECT count(*), DATE_FORMAT(doc.create_time, '%Y-%m-%d') AS t FROM sale_order doc WHERE DATE_FORMAT(doc.create_time, '%Y') = '2017' GROUP BY t ORDER BY NULL"}
    """
    order_total_num = {}
    

    for k,v in sql.items():
        #print v
        cursor.execute(v)
        result = cursor.fetchall()#获取查询结果
        print result
        if result:
            for x in result:
                for y in x:
                    order_total_num[k]=y
        else:
            return False

    #print "order_total_num",order_total_num
    
    cursor.close()
    db.close()

    return order_total_num
  

@log
def result_for_chart():
    #订单情况
    import matplotlib.pyplot as plt
    sql = {"CHECK":"SELECT COUNT(*) FROM sale_order WHERE `status`='CHECK' AND merchant_id=1 ;",
           "INIT":"SELECT COUNT(*) FROM sale_order WHERE `status`='INIT' AND merchant_id=1 ;",
           "DELIVERY":"SELECT COUNT(*) FROM sale_order WHERE `status`='DELIVERY' AND merchant_id=1 ;",
           "total":"SELECT COUNT(*) FROM sale_order WHERE  merchant_id=1 ;"}

    result = get_sku_for_Db(sql)
    print result
    
    plt.rcParams['font.sans-serif']=['SimHei']#用来正常显示中文标签
    plt.rcParams['axes.unicode_minus']=False#用来正常显示负号
    
    biaoqian = u"待审核",u"已出库",u"已审核",u"其他"
    sizes = result["INIT"], result["DELIVERY"], result["CHECK"], result["total"] - (result["INIT"]+result["DELIVERY"]+result["CHECK"])# 不需要传入总量
    yanse = "lightblue", "lightgray", "yellow", "pink"
    explode = 0.15, 0.15, 0.15, 0.15  
    plt.pie(sizes,
            explode=explode,
            labels=biaoqian,
            colors=yanse,
            autopct="%1.1f%%",
            shadow=True,
            startangle=100)
    plt.axis("equal")
    plt.show()


def result_for_x():
    import numpy as np
    import matplotlib.pyplot as plt
    #from pylab import *

    x = np.arange(-5.0, 5.0, 0.02)
    y1 = np.sin(x)

    plt.figure(1)
    plt.subplot(211)
    plt.plot(x, y1)

    plt.subplot(212)
    #设置x轴范围
    xlim(-2.5, 2.5)
    #设置y轴范围
    ylim(-1, 1)
    plt.plot(x, y1)


if __name__ == "__main__":
    sql = {"CHECK":"SELECT COUNT(*) FROM sale_order WHERE `status`='CHECK' AND merchant_id=1 ;",
           "INIT":"SELECT COUNT(*) FROM sale_order WHERE `status`='INIT' AND merchant_id=1 ;",
           "DELIVERY":"SELECT COUNT(*) FROM sale_order WHERE `status`='DELIVERY' AND merchant_id=1 ;",
           "total":"SELECT COUNT(*) FROM sale_order WHERE  merchant_id=1 ;"}
    result = get_sku_for_Db(sql)
    print result
   

